﻿using System;
using System.Runtime.CompilerServices;
using Core.Extension;
using Core.Mgr._EventSys;
using Core.Mgr._ResMgr;
using Core.Mgrs;
using Logic.Global;
using Logic.Global.UI;
using UnityEngine;

namespace Core.Base.Module
{
    /// <summary>
    /// 是所有模块的基类
    /// </summary>
    public class BaseModule
    {
        private ModuleAttribute _moduleAttribute;

        /// <summary>
        /// 是否为主模块
        /// </summary>
        public bool IsMainModule => SceneName.Equals("Main");

        /// <summary>
        /// 该模块对应的场景名
        /// </summary>
        public string SceneName => _moduleAttribute.SceneName;

        /// <summary>
        /// 当模块卸载时
        /// </summary>
        public Action onUnload;

        /// <summary>
        /// 当加载开始
        /// </summary>
        /// <param name="moduleAttribute">模块的属性</param>
        /// <param name="tuple">传入的数据</param>
        /// <param name="onFinish">当模块加载完成</param>
        /// <param name="onFail">当模块加载失败</param>
        public virtual void OnLoadStart(ModuleAttribute moduleAttribute, ITuple tuple = null, Action onFinish = null,
            Action onFail = null)
        {
            _moduleAttribute = moduleAttribute;
            // 不是全局模块的话，加载对应的场景
            if (IsMainModule)
            {
                onFinish?.Invoke();
            }
            else
            {
                UIMgr.Ins.OnOpen<LoadUI>();
                ResMgr.LoadSceneAsync(SceneName,
                    delegate(float progress)
                    {
                        EventMgr.Notify(ELoadUI.OnUpdateProgress, ValueTuple.Create(progress));
                    }, delegate
                    {
                        onFinish?.Invoke();
                        OnLoadFinished(tuple);
                    }, delegate
                    {
                        UIMgr.Ins.OnClose<LoadUI>();
                        onFail?.Invoke();
                    });
            }
        }

        /// <summary>
        /// 当模块场景加载完成
        /// </summary>
        /// <param name="tuple">传入的数据</param>
        protected virtual void OnLoadFinished(ITuple tuple = null)
        {
            GameObject.Find("EditorCamera")?.SetActive(false);
        }

        /// <summary>
        /// 当被卸载
        /// </summary>
        public virtual void OnUnload()
        {
            Util.ClearMemory();
            onUnload?.Invoke();
        }
    }
}